import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import ReactQuill from 'react-quill'
import { useState, useRef, useEffect } from 'react'
import { useStore } from '@/store'
import { getArticles, submitArticles, updateArticles } from '@/api'
import './index.scss'
import 'react-quill/dist/quill.snow.css'
import { useSearchParams } from 'react-router-dom'
const { Option } = Select

const PublishPage = () => {
  const { channelStore } = useStore()
  const [fileList, setFileList] = useState([])
  const [typeState, setTypeState] = useState(1)
  const [params] = useSearchParams()
  const id = params.get('id')
  const imgCon = useRef([])
  const formRef = useRef()
  // 回写数据
  useEffect(() => {
    const getDetail = async () => {
      const res = await getArticles(id)
      const { cover, ...formValue } = res.data
      const imgcurr = cover.images.map(url => ({ url }))
      formRef.current.setFieldsValue({ ...formValue, type: cover.type })
      setFileList(imgcurr)
      setTypeState(cover.type)
      imgCon.current = imgcurr
    }
    if (id) {
      getDetail()
    }
  }, [])
  useEffect(() => {
    if (!id) {
      setFileList([])
      setTypeState(1)
      imgCon.current = []
      formRef.current.resetFields()
    }
  }, [id])
  // 提交数据
  const onFinish = async (value) => {
    const { channel_id, content, title, type } = value
    const params = {
      channel_id,
      content,
      title,
      type,
      cover: {
        type: type,
        images: fileList.map(item => item.url)
      }
    }
    if (id) {
      await updateArticles(id, params)
    } else {
      await submitArticles(params)
    }
  }
  const onUploadChange = info => {
    const fileList = info.fileList.map(file => {
      if (file.response) {
        return {
          url: file.response.data.url
        }
      }
      return file
    })
    imgCon.current = fileList
    setFileList(fileList)
  }
  const typeChange = (e) => {
    setTypeState(e.target.value)
    if (e.target.value === 1) {
      const firstImg = imgCon.current[0]
      setFileList(!firstImg ? [] : [firstImg])
    } else if (e.target.value === 3) {
      setFileList(imgCon.current)
    }
  }
  return (
    <div className="publish">
      <Card
        title={
          <Breadcrumb items={[
            {
              title: <a href="/home">首页</a>,
            },
            {
              title: (id ? '编辑' : '发布') + '文章',
            },
          ]}>
          </Breadcrumb>
        }

      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1 }}
          onFinish={onFinish}
          ref={formRef}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              {
                channelStore.channelList.map(el => (
                  <Option key={el.id} value={el.id}>{el.name}</Option>
                ))
              }
            </Select>
          </Form.Item>

          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={typeChange}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {
              typeState > 0 && (
                <Upload
                  name="image"
                  listType="picture-card"
                  className="avatar-uploader"
                  showUploadList
                  action="http://geek.itheima.net/v1_0/upload"
                  fileList={fileList}
                  onChange={onUploadChange}
                  multiple={typeState > 1}
                  maxCount={typeState}
                >
                  <div style={{ marginTop: 8 }}>
                    <PlusOutlined />
                  </div>
                </Upload>
              )
            }
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入文章内容"
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                {id ? '更新' : '发布'}文章
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
export default PublishPage